package com.ysalliance.getFan.organization.ui.h5;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.example.zhouwei.library.CustomPopWindow;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultWebClient;
import com.ysalliance.getFan.organization.Bean.TaskBean;
import com.ysalliance.getFan.organization.Bean.bus.TaskDeleteIsNeedFresh;
import com.ysalliance.getFan.organization.Bean.bus.TaskUpdateIsNeedFresh;
import com.ysalliance.getFan.organization.LucasUtil;
import com.ysalliance.getFan.organization.R;
import com.ysalliance.getFan.organization.myview.dialog.ChooseDialog;
import com.ysalliance.getFan.organization.network.Network;
import com.ysalliance.getFan.organization.ui.task.AddTaskActivity;
import com.ysalliance.getFan.organization.ui.base.LucasBaseActivity;
import com.ysalliance.getFan.organization.ui.task.UpdateTaskActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import androidx.annotation.NonNull;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

import static com.ysalliance.getFan.organization.FanerConstant.ENTER;


/**
 * 一般的网页
 *
 * @author lucas
 * created at 2020-01-23 21:19
 */
public class TaskH5Activity extends LucasBaseActivity {


    @BindView(R.id.web_container)
    LinearLayout web_container;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.img_task_manager)
    ImageView img_task_manager;


    protected AgentWeb mAgentWeb;
    //请求的网址
    private String askUrl = "";

    private TaskBean taskBean;
    private CustomPopWindow mCustomPopWindow;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void beforeView() {
        super.beforeView();
        EventBus.getDefault().register(mContext);
    }

    @Override
    public int bindContentView() {
        return R.layout.activity_task_h5;
    }

    @Override
    public void afterView() {
        super.afterView();

        taskBean = (TaskBean)getIntent().getSerializableExtra("task_info");

        askUrl = getIntent().getStringExtra("url");
        LogUtils.e("h5页面收到的url:", askUrl);

        //展示缓冲条
        mProgressBarHandler.show(); // To show the progress bar




        // 编辑任务 or 删除任务
        img_task_manager.setOnClickListener(v->{
            showPopMenu(img_task_manager);
        });


    }





    /** popupwindow  */
    private void showPopMenu(View view) {
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.pop_task_menu_class, null);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int  mShowMorePopupWindowWidth = -contentView .getMeasuredWidth();
        int  mShowMorePopupWindowHeight = -contentView .getMeasuredHeight();


        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(mContext)
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .create()
                .showAsDropDown(view,mShowMorePopupWindowWidth + 100,0);
    }
    private void handleLogic(View contentView){
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mCustomPopWindow!=null){
                    mCustomPopWindow.dissmiss();
                }
                String showContent = "";
                switch (v.getId()){
                    case R.id.menu1_task_edit:

                        //编辑任务
                        Intent intent = new Intent(Utils.getApp(), UpdateTaskActivity.class);
                        intent.putExtra("task", taskBean);
                        ActivityUtils.startActivity(intent);

                        break;
                    case R.id.menu2_delete_task:
                        //删除任务
                        ChooseDialog chooseDialog = new ChooseDialog(mContext,"确认删除", "不删了", "一旦删除，任务下所有打卡都将被删除，且不可恢复。确定要删除任务"){
                            @Override
                            public void left() {
                                super.left();
                                delete_task(taskBean.getId());
                            }

                            @Override
                            public void right() {
                                super.right();
                            }
                        };
                        chooseDialog.show();

                        break;

                }
            }
        };
        contentView.findViewById(R.id.menu1_task_edit).setOnClickListener(listener);
        contentView.findViewById(R.id.menu2_delete_task).setOnClickListener(listener);
    }



    public void initData() {
        //同步cookies
//        AgentWebConfig.syncCookie("https://api.getfan.cn", LucasUtil.pref_get(mContext,"cookie"));
        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(web_container, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
                .closeIndicator()    //取消进度条     默认是.useDefaultIndicator()
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
                .interceptUnkownUrl() //拦截找不到相关页面的Scheme
                .createAgentWeb()
                .ready()
                .go(askUrl);



        mAgentWeb.getWebCreator().getWebView().setWebContentsDebuggingEnabled(true);


        if(mAgentWeb!=null){
            //注入对象
            mAgentWeb.getJsInterfaceHolder().addJavaObject("android",new AndroidInterface(mAgentWeb,mContext,taskBean));

        }

    }


    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //do you  work
            Log.e("Info", "BaseWebActivity onPageStarted");
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            CookieManager cookieManager = CookieManager.getInstance();
            String CookieStr = cookieManager.getCookie(url);
            LogUtils.d("Cookies:", CookieStr);

            super.onPageFinished(view, url);
        }


    };


    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //do you work
            Log.i("Info", "onProgress:" + newProgress);

            if (newProgress == 100) {
                mProgressBarHandler.hide();
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            //设置标题
            if (tv_title != null) {
                tv_title.setText(title);
            }
        }
    };


    @Override
    public void onBackPressed() {
        if(askUrl.equals(ENTER)){
            super.onBackPressed();
        }else {
            if (!mAgentWeb.back()) {
                super.onBackPressed();
            }
        }

    }


    @Override
    public void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }


    @Override
    public void onResume() {
        initData();
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }




    /**  删除任务   */
    public void delete_task(String task_id){

        disposable = Network.getUtilApi()
                .delete_task(task_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(@NonNull ResponseBody responseBody) throws Exception {
                        String res = responseBody.string();
                        LogUtils.json("获取组织结构的返回", res);

                        JSONObject jsonObject = new JSONObject(  res  );
                        if(LucasUtil.isok(jsonObject.optString("status"))){

                            ToastUtils.showShort("删除成功");
                            EventBus.getDefault().postSticky(new TaskDeleteIsNeedFresh(true));
                            onBackPressed();

                        }else {
                            ToastUtils.showShort(jsonObject.optString("message"));
                        }
                    }

                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                        LogUtils.e(throwable.getMessage());
                        Toast.makeText(mContext,"网络请求失败！", Toast.LENGTH_SHORT).show();
                    }
                });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TaskUpdateIsNeedFresh taskUpdateIsNeedFresh) {
        /* Do something */
        LogUtils.e("收到了是否需要刷新任务详情页与否的提示");
        /* Do something */
        if(taskUpdateIsNeedFresh.isIs_need_fresh()){
            mAgentWeb.getJsAccessEntrace().quickCallJs("reset" );
        }
    }






}
